package com.pay.ioopos.service;

import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import com.aggregate.pay.sanstar.SanstarApiFactory;
import com.aggregate.pay.sanstar.bean.Result;
import com.aggregate.pay.sanstar.bean.TerminalSdkResult;
import com.aggregate.pay.sanstar.support.Client;
import com.dongqing.payreport.PayReport;
import com.dongqing.payreport.PayReport.InitCallBack;
import com.pay.ioopos.ApiFactory;
import com.pay.ioopos.Application;
import com.pay.ioopos.DataFactory;
import com.pay.ioopos.sqlite.SettingHelper;

import java.util.HashMap;


public class ReportService extends IntentService {
    private static boolean sdkInited = false;
    private static Thread sdkThread;
    private TerminalSdkResult sdkParams;
    private Handler handler = new Handler();

    public ReportService() {
        super("ReportService");
    }

    public static boolean isSdkInited() {
        return sdkInited;
    }

    public static void resetService() {
        Application.getContext().startService(new Intent(Application.getContext(), ReportService.class));
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        sdkInited = false;
        if (null != sdkThread) {
            sdkThread.interrupt();
        }
        sdkThread = new Thread(() -> {
            if (null == Looper.myLooper()) {
                Looper.prepare();
            }
            try {
                doWhile();
            } catch (InterruptedException ignored) {

            }
        });
        sdkThread.start();
    }

    private void doWhile() throws InterruptedException {
        while(true) {
            try {
                String key;
                String merchNo;
                if (NetworkService.isNetworkAvailable()
                        && null != (key = DataFactory.getDataStore().getTransKey())
                        && !key.equals(SettingHelper.INIT_KEY)
                        && null != (merchNo = DataFactory.getDataStore().getMerchNo())
                        && !merchNo.isEmpty()) {
                    loadSdkParams();
                    initSdkReport();
                }
            } catch (Exception e) {
                showToast(String.format("微信SDK-INIT：%s", e.getMessage()));
            }
            Thread.sleep(1500000); // 25分钟
        }
    }

    private void loadSdkParams() throws Exception {
        Client<Void, TerminalSdkResult> client = SanstarApiFactory.terminalSdk(ApiFactory.initApi());

        Result<TerminalSdkResult> apiResult = client.execute(null);

        if (apiResult.getStatus() != Result.Status.OK) {
            throw new Exception(apiResult.getMessage());
        }

        sdkParams = apiResult.getData();
    }

    private void initSdkReport() {
        if (null == sdkParams) {
            return;
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", sdkParams.getAppId());
        map.put("mch_id", sdkParams.getMchId());
        map.put("sub_mch_id", sdkParams.getSubMchId());
        map.put("timestamp", sdkParams.getTimestamp());
        map.put("nonce_str", sdkParams.getNonceStr());
        map.put("serial_no", sdkParams.getSerialNo());
        map.put("device_category", sdkParams.getDeviceCategory());
        map.put("device_class", sdkParams.getDeviceClass());
        map.put("device_model", sdkParams.getDeviceModel());
        map.put("mch_sign", sdkParams.getMchSign());
        PayReport.getInstance(this).initReport(map, new InitCallBack() {
            @Override
            public void success() {
                sdkInited = true;
            }

            @Override
            public void failed(String msg) {
                showToast("微信SDK-INIT：" + msg);
            }
        });

    }

    private void showToast(String msg) {
        if (null == Looper.myLooper()) {
            Looper.prepare();
        }
        handler.post(() -> Toast.makeText(this, msg, Toast.LENGTH_SHORT).show());
    }
}
